﻿using System;
using System.Collections.Generic;
using System.Data.OleDb;
using System.Linq;
using System.Text;

namespace Students
{
    public class DACourse
    {
        AccessBase bases;
        public List<BOCourses> GetCourses(int studentId, int pageIndex, int pageSize, out int totalPages)
        {
            try
            {
                totalPages = 0;
                int startIndex = pageIndex * pageSize;

                List<BOCourses> lst = new List<BOCourses>();
                bases = new AccessBase();
                bases.cnn.Open();
                OleDbDataReader reader = null;
                OleDbCommand command = new OleDbCommand("SELECT Courses.ID,Courses.CourseName,Courses.CourseSubject,Courses.CourseNumber,Courses.CourseDescription,StudentToCourse.Term FROM  Courses , StudentToCourse WHERE Courses.Id= StudentToCourse.CourseId and StudentToCourse.StudentId=@studentId", bases.cnn);
                command.Parameters.AddWithValue("@studentId", studentId);
                reader = command.ExecuteReader();
                while (reader.Read())
                {
                    lst.Add(new BOCourses
                    {
                        Id = int.Parse(reader[0].ToString()),
                        CourseName = reader[1].ToString(),
                        CourseNumber = reader[2].ToString(),
                        CourseSubject = reader[3].ToString(),
                        CourseDescription = reader[4].ToString(),
                        Term = reader[5].ToString()
                    });
                }
                bases.cnn.Close();
                if (lst.Count() == 0)
                    return null;

                int totalRecords = lst.Count;
                totalPages = totalRecords / pageSize * pageSize == totalRecords ? totalRecords / pageSize : totalRecords / pageSize + 1;

                return lst.Skip(startIndex).Take(pageSize).ToList();
            }
            catch
            {
                totalPages = 0;
                return null;
            }
        }
    }
}
